<?php
class auth
{
	var $user_id = 0;
	var $username = null;
	var $password = null;
	var $locked = false;
	var $salt = SALT;
	var $domain = BASE_URL;
	var $save_login = false;

	function __construct()
	{
		global $db;
			
		$this->user_id = 0;
		$this->username = "guest";
		$this->locked = false;
			
		if(!$this->check_session()) $this->check_cookie();
			
		return $this->locked;
	}

	function check_session()
	{
		global $session;
		if(!empty($session->auth_username) && !empty($session->auth_password))
		return $this->check($session->auth_username, $session->auth_password);
		else
		return false;
	}

	function check_cookie()
	{
		global $cookie,$session;
		if(!empty($_COOKIE['auth_username']) && !empty($_COOKIE['auth_password'])){
			return $this->check($_COOKIE['auth_username'], $_COOKIE['auth_password']);
		}else{
			return false;
		}
	}

	function login($username, $password)
	{
		global $session,$cookie;
		global $db;
		$password = md5(htmlentities($password) . $this->salt);
		$query =  "SELECT * FROM ".TBL_USERS."
				  WHERE username = '".$db->escape($username)."' 
				  AND password = '". $password ."'";
		if($row = $db->get_row($query))
		{
			$this->user_id = $row->user_id;
			$this->username = $row->username;
			$this->locked = true;

			$session->auth_username = $username;
			$session->auth_password = $password;
			setcookie('auth_username', $username, time() + 60*60*24*30,'/');
			setcookie('auth_password', $password, time() + 60*60*24*30,'/');
			return true;
		}
		return false;
	}

	function check($username, $password)
	{
		global $db,$session;
		$query = "SELECT * FROM ".TBL_USERS.
				 " WHERE username = '".$db->escape($username)."'";
		if($row = $db->get_row($query))
		{
			if($password == $row->password)
			{
				$session->auth_username = $_COOKIE['auth_username'];
				$session->auth_password = $_COOKIE['auth_password'];		
				$this->user_id = $row->user_id;
				$this->username = $row->username;
				$this->locked = true;
				return true;
			}
		}
		return false;
	}

	function logout()
	{
		global $session,$cookie;
		$this->user_id = 0;
		$this->username = "guest";
		$this->locked = false;

		unset($session->auth_username);
		unset($session->auth_password);
		$session->destroy();
		setcookie('auth_username', $username, time() - 3600,'/');
		setcookie('auth_password', $username, time() - 3600,'/');
	}
}
?>